package com.task.manager.util;

import java.lang.reflect.Type;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;

/**
 * Gson转换json类
 * 
 * @author xunzheng
 * 
 */
public class GsonUtil {
	private static Gson gson = new Gson();
	private static Log log = LogFactory.getLog(GsonUtil.class);

	/**
	 * json字符串转换简单普通类
	 * 
	 * @param jsonData
	 * @param type
	 * @return
	 */
	public static <T> T jsonToObject(String jsonData, Class<T> type) {
		try {
			T result = gson.fromJson(jsonData, type);
			return result;
		} catch (Exception e) {
			log.error("转换json失败，原文：" + jsonData);
		}
		return null;
	}

	/**
	 * json字符串转换带有泛型的对象
	 * 
	 * @param jsonData
	 * @param typeToken
	 * @return
	 */
	public static <T> T jsonToObjectWithT(String jsonData, TypeToken<T> typeToken) {
		try {
			Type type = typeToken.getType();
			T result = gson.fromJson(jsonData, type);
			return result;
		} catch (Exception e) {
			log.error("转换json失败，原文：" + jsonData);
		}
		return null;
	}
	
	public static <T> T jsonToObjectWithT(String jsonData,GsonBuilder builder,TypeToken<T> typeToken) {
		try {
			Gson newGson = gson;
			if(builder != null){
				newGson = new GsonBuilder().create();
			}
			Type type = typeToken.getType();
			T result = newGson.fromJson(jsonData, type);
			return result;
		} catch (Exception e) {
			log.error("转换json失败，原文：" + jsonData);
		}
		return null;
	}

	/**
	 * 对象转换json字符串
	 * 
	 * @param object
	 * @return
	 */
	public static String objectToJson(Object object) {
		try {
			String result = gson.toJson(object);
			return result;
		} catch (Exception e) {
			log.error("转换json失败", e);
		}
		return null;
	}

	/**
	 * 对象转换json字符串带格式的
	 * 
	 * @param object
	 * @return
	 */
	public static String objectToJsonWithDateFormat(Object object, String patten) {
		try {
			Gson gson = new GsonBuilder().setDateFormat(patten).create();
			String result = gson.toJson(object);
			return result;
		} catch (Exception e) {
			log.error("转换json失败", e);
		}
		return null;
	}

	/**
	 * 使用自定义的gsonBuilder new GsonBuilder().registerTypeAdapter(java.sql.Date.class, new SQLDateTypeAdapter()).create();
	 * 
	 * @param object
	 * @return
	 */
	public static String objectToJsonWithTypeAdpter(Object object, GsonBuilder gsonBuilder) {
		try {
			Gson gson = gsonBuilder.create();
			String result = gson.toJson(object);
			return result;
		} catch (Exception e) {
			log.error("转换json失败", e);
		}
		return null;
	}
}
